/*
 * jQuery UI themeselect widget
 *
 * Copyright (c) 2010 nme.pl
 * Licensed under New BSD License (http://www.opensource.org/licenses/bsd-license.php)
 *
 */

(function($) {

$.widget('ui.themeselect', {
	_init: function() {
		var self = this;
		// fill element structure
		this.element
			.addClass('theme-select');
    	$('<form method="post" action="'+this.options.post+'">'+
			'<fieldset>'+
			  '<select name="theme">'+
			  '</select>'+
			'</fieldset>'+
		  '</form>').appendTo(this.element);
		var select = this.element.find('select');
		// setup thumbnails and fill select with options
		var theme = this.options.current;
		select.append('<option value="'+theme+'" class="theme-option theme-'+theme+'">'+theme+'</option>');
		var thumbnails = [];
		for (var i in this.options.themes) {
			if (this.options.themes.hasOwnProperty(i)) {
				if (this.options.themes[i] !== theme) {
					select.append('<option value="'+this.options.themes[i]+'" class="theme-option theme-'+this.options.themes[i]+'">'+this.options.themes[i]+'</option>');
				}
				thumbnails.push({find: '.theme-'+this.options.themes[i]});
			}
		}
		// make it selectmenu jquery-ui widget
		select.selectmenu({
			style: 'dropdown',
			width: '14em',
			menuWidth: '14em',
			icons: thumbnails,
			maxHeight:200
		});
		// make selectmenu reactive
		select.change(function(){
			self.select($(this).attr('value'));
		});
	},
	select: function(new_theme) {
		var before = this.options.before, after = this.options.after;
		var before_length = before.length, found = false;
		$('link').each(function() {
			var url = $(this).attr('href');
			if (url.substr(0,before_length) == before) {
				found = true;
				$(this).attr('href',before+new_theme+after);
			}
		});
		if (!found) {
			$('<link rel="stylesheet" href="'+before+new_theme+after+'" type="text/css"/>').appendTo('head');
		}
	},
	disabled: function() {
		this.element.addClass('ui-state-disabled');
	},
	enabled: function() {
		this.element.removeClass('ui-state-disabled');
	},
	destroy: function() {
		this.element
			.removeClass('theme-select')
			.html('');
	}
});

$.extend($.ui.themeselect, {
	defaults: {
		post:'/',
        before:'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/',
        after:'/jquery-ui.css',
		themes:[
            'black-tie',
            'blitzer',
            'cupertino',
            'dark-hive',
            'dot-luv',
            'eggplant',
            'excite-bike',
            'flick',
            'hot-sneaks',
            'humanity',
            'le-frog',
            'mint-choc',
            'overcast',
            'pepper-grinder',
            'redmond',
            'smoothness',
            'south-street',
            'start',
            'sunny',
            'swanky-purse',
            'trontastic',
            'ui-darkness',
            'ui-lightness',
            'vader'
		],
		current:'blitzer'
	}
});

})(jQuery);
